package com.dabbo.starship.container;

import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import com.dabbo.starship.interfaces.Container;
import com.dabbo.starship.interfaces.UniverseInterface;
import com.dabbo.starship.shared.SpaceLocation;

public class Universe extends java.rmi.server.UnicastRemoteObject implements UniverseInterface {
	
	private static final long serialVersionUID = -2440284809991250045L;
	
	protected HashMap<Integer, Container> entity;
	
	public Universe() throws RemoteException {
		entity = new HashMap<Integer, Container>();
		// Add static universe objects
		for (int i = 0; i < 5; i++) {
			Container tempShip = createNewShip("AI Ship #" + i);
			tempShip.setPlayerID("System");
			entity.put(tempShip.hashCode(), tempShip);
		}
	}
	
	@Override
	public Container initPlayerShip(String playerID) throws RemoteException {
		System.out.println("initPlayerShip(" +  playerID + ") called.");
		System.out.println("    Universe size : " + entity.size());
		Set<Entry<Integer, Container>> set = entity.entrySet(); 
		Iterator<Entry<Integer, Container>> i = set.iterator(); 
		while(i.hasNext()) { 
			Map.Entry<Integer, Container> ent = (Map.Entry<Integer, Container>) i.next();
			Container unit = (Container) ent.getValue();
			System.out.println("        : (e) Aseet [" + unit.getAssetName() + "] Original Owner [" + unit.getPlayerID() + "]");
			if (unit.getPlayerID().equalsIgnoreCase(playerID)) {
				System.out.println("    ^ Existing player ship in place, using this asset.");
				return unit;
			}
		} 
		Container newShip = createNewShip("Unknown Player Ship"); 
		newShip.setPlayerID(playerID);
		entity.put(newShip.hashCode(), newShip);
		System.out.println("    Unable to find asset for player, new asset created.");
		return newShip;
	}

	private Container createNewShip(String assetName) throws RemoteException {
		Container newShip = new ContainerShip(assetName);
		newShip.setDirection(ContainerBase.DIR_NORTH);
		int ry = new Double((Math.random() * 25000)).intValue();
		int rx = new Double((Math.random() * 25000)).intValue();
		SpaceLocation sl = new SpaceLocation();
		sl.setCoX(rx);
		sl.setCoY(ry);
		newShip.setPosition(sl);
		return newShip;
	}
	
	@Override
	public void tick() throws RemoteException {
		for (Container obj : entity.values()) {
			obj.tick();
			if (obj.getPowerOutput() < 0) {
				obj.powerFailure();
			}
		}
	}

	@Override
	public Container getContainer(int containerKey) throws RemoteException {
		return entity.get(containerKey);
	}
	

}
